<template>
    <div class="content">
        <!-- 手记 顶部搜索栏 -->
        <div class="m-content">
            <div class="logoBlock">
                <!-- <el-avatar :size="50"></el-avatar>
                <div>用户名</div> -->
                <a href="#" title="手记">
                    <img src="~/assets/img/articleHeader-logo.png" width="100%" height="100%" alt="手记">
                </a>
            </div>
            <div class="searchArticle">
                <el-input placeholder="搜索感兴趣的知识和文章" class="input-with-select" v-model="mBlogQuery.searchArticleContent"   @keydown.enter.native="searchArticle()">    
                </el-input><el-button slot="append" icon="el-icon-search" @click="searchArticle()"></el-button>
            </div>
            <div class="writeArticle">
                <el-button type="primary" icon="el-icon-edit" @click="editArticle()">写文章</el-button>
            </div>
        </div>

        <el-form ref="editForm" status-icon :model="editForm" :rules="rules" label-width="80px">
          <el-form-item label="标题" prop="title">
              <el-input v-model="editForm.title"></el-input>
          </el-form-item>
          <el-form-item label="摘要" prop="description">
              <el-input type="textarea" v-model="editForm.description"></el-input>
          </el-form-item>
          <el-form-item label="类别" prop="blogType">
            <el-select v-model="editForm.blogType" placeholder="文章类别">
              <el-option v-for="blogType in blogTypeList" :key="blogType.id" :label="blogType.title" :value="blogType.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <mavon-editor v-model="editForm.content" ref=md  @imgAdd="imgAdd" :toolbars="toolbars"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">立即修改</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
    </div>
</template>

<script>

import blogApi from '@/api/blog'


export default {

    asyncData({ params, error }) {
     return {articleId: params.id}
   },

    data() {
      return {
        mBlogQuery: {
            blogType: -1,
            searchArticleContent: ''
        },//根据博客类别和相关信息查询

        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: false, // 标记
          superscript: false, // 上角标
          subscript: false, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: false, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: false, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: false, // 下一步
          trash: false, // 清空
          save: false, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: false, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
          boxShadow: false
        },

        //编辑博客
        editForm: {
          title: '',
          description: '',
          content: '',
          blogType: '',
          userId: '',
          nickname: ''
        },

        //表单效验规则
        rules: {
          title: [
            {required: true, message: '请输入标题', trigger: 'blur'},
            {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}
          ],
          description: [
            {required: true, message: '请输入摘要', trigger: 'blur'}
          ],
          blogType: [
            { required: true, message: '请选择文章类别', trigger: 'change' }
          ],
        },

        blogTypeList: [], //博客类型列表


      }
    },

    created() {
      this.getBlogTypeList(),
      this.getArticle()
    },

    methods: {

        //根据文章id获取文章信息(回显)
        getArticle() {
            blogApi.getArticle(this.articleId)
              .then(response => {
                this.editForm = response.data.data.article
            })
        },

        //markdown编辑器的 图片上传功能
        imgAdd(pos, $file) {
          console.log('图片上传')
          console.log(pos, $file);

          var formdata = new FormData();
          formdata.append('image', $file);
          console.log(formdata)
          blogApi.uploadOssFile(formdata)
            .then(response => {
                console.log('请求成功')
                console.log(response.data.data.url)
                this.$refs.md.$img2Url(pos, response.data.data.url)
            })

        },

        //查询博客类型列表
        getBlogTypeList() {
            blogApi.getBlogTypeList()
                .then(response => {
                    this.blogTypeList = response.data.data.items
                })
        },


        //提交表单
        submitForm() {
          //验证表单
          this.$refs['editForm'].validate((valid) => {
          if (valid) {//通过验证
            //发起修改文章请求
            blogApi.updateArticle(this.editForm)
                .then(response => {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.$router.push({path:'/article/' + this.articleId})
                })
                .catch(error => {
                    console.log(error)
                })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
        },

        editArticle() {
            this.$message({
                message: '请先编辑完当前文章再写另一篇文章!',
                type: 'error'
            });
        },

        //根据文章标题、简介、内容搜索文章
        searchArticle() {
            if (this.mBlogQuery.searchArticleContent.length == 0) {
                this.$message({
                    message: '请先输入关键词',
                    type: 'warning'
                });
            } else {
                this.$router.push({path:'/article/', query:{searchArticleContent:this.mBlogQuery.searchArticleContent}})
            }
        }

    },
}

</script>

<style scoped>
  .content {
    /* 上 右 下 左 */
    margin: 10px 0px 0px 0px;
    /* padding-bottom: 100px; */
  }

  .m-content {
    max-width: 1150px;
    margin: 0 auto;
    align-items: center;
    display: flex;
    position: relative;
  }
  .logoBlock {
    width: 10%;
    padding: 5px;
    display: inline-block;
  }
  .searchArticle {
    vertical-align: top;
    display: inline-block;
    position: absolute;
    right: 130px;
  }
  .el-input {
    /* 搜索框长度 */
    width: 400px;
  }
  .writeArticle {
    background-color: cadetblue;
    /* https://blog.csdn.net/qq_44131760/article/details/104755826  解释了为什么使用 vertical-align*/
    vertical-align: top;
    display: inline-block;
    position: absolute;
    right: 10px;
  }

  .el-form {
    max-width: 1150px;
    margin: 0 auto;
  
  }

  </style>